<template>
<div>
  <div>
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input  v-model="searchForm.name" placeholder="请输入姓名"></el-input>
    </el-form-item>
    <el-form-item label="邮箱">
      <el-input v-model="searchForm.email"  placeholder="请输入邮箱"></el-input>
    </el-form-item>
    <el-form-item   label="地址">
      <el-input  v-model="searchForm.address" placeholder="请输入地址"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search" >查询</el-button>
    </el-form-item>
  </el-form>
  </div>
  <div style="padding-bottom:10px;">
     <el-button type="primary" @click="addDialog" >新增</el-button>
  </div>
  <div>
    <!--表格内容-->
    <el-table
      ref="list"
      :data="tableData"
      style="width: 100%"
      border
      stripe
      highlight-current-row
      @row-click="handleRowClick"
      @select-all="handleCheckedAllAndCheckedNone"
      @select="handleCheckedAllAndCheckedNone">
      <el-table-column
        type="selection"
        width="45"
        align="center">
      </el-table-column>
      <el-table-column
        type="index"
        label="序号"
        width="50">
      </el-table-column>
      <el-table-column
        property="createTime"
        label="创建日期"
        width="200"
        sortable>
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 5px">{{scope.row.createTime}}</span>
        </template>
      </el-table-column>
      <el-table-column
        property="name"
        label="姓名"
        width="100">
      </el-table-column>
      <el-table-column
        property="address"
        width="230"
        label="地址">
      </el-table-column>
       <el-table-column
        property="age"
        width="80"
        label="年龄">
      </el-table-column>
       <el-table-column
        property="email"
        width="180"
        label="邮箱">
      </el-table-column>
      <el-table-column
        property="updateTime"
        label="更新日期"
        width="200"
        sortable>
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 5px">{{scope.row.updateTime}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="130"
        align="center">
        <template slot-scope="scope">
          <el-button circle icon="el-icon-edit-outline" type="primary" title="编辑" size="small"
            @click="rowEdit(scope.$index, scope.row)"></el-button>
          <el-button circle icon="el-icon-delete" type="danger" title="删除" size="small"
            @click="rowDel(scope.$index, scope.row, $event);"></el-button>
        </template>
      </el-table-column>
    </el-table>
     <!--分页-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchForm.pageNnum" 
      :page-size="searchForm.pageSize" 
      :total="total"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!--编辑-弹出层-->
    <el-dialog
      :title=dialogTitle
      :visible.sync="isShowEditDialog"
      width="430px"
      @close="dialogClose">
      <el-form
        ref="formFileds"
        :model="formFileds"
        label-width="80px"
        :rules="rules">
        <template v-if="judeType===1">
        <el-form-item label="创建日期">
          <el-date-picker v-model="formFileds.createTime" type="date" format="yyyy 年 MM 月 dd 日" value-format="timestamp" :editable="false" :clearable="false"></el-date-picker>
        </el-form-item>
        </template>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formFileds.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input type="number"  :min="0" v-model="formFileds.age"></el-input>
        </el-form-item>
         <el-form-item label="地址" prop="address">
          <el-input v-model="formFileds.address"></el-input>
        </el-form-item>
         <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="formFileds.email"></el-input>
        </el-form-item>
        <el-form-item>
          <template v-if="judeType === 1">
             <el-button type="primary" @click="addUser" :disabled="formFileds.name===''||
                    formFileds.address===''||
                    formFileds.email===''" 
                    class="pull-right margin-l-25">确定</el-button>
          </template>
          <template v-else>
             <el-button type="primary" @click="edit" :disabled="formFileds.name===''||
                    formFileds.address===''||
                    formFileds.email===''"  class="pull-right margin-l-25">确定</el-button>
          </template>
          <el-button @click="close" class="pull-right">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</div>
</template>

<script>
  export default {
    name: "Table",
    data() {
      return {
        formFileds: {
          age: '',
          email: '',
          createTime: '',
          name: '',
          address: '',
          id: ''
        },
        searchForm: {
          name: '',
          email: '',
          address: '',
          pageNum: 1,
          pageSize: 5
        },
        total: 0,
        rules: {
          name: [
            {required: true, message: '姓名不能为空', trigger: 'blur'}
          ],
          address: [
            {required: true, message: '地址不能为空', trigger: 'blur'}
          ],
          email: [
            {required: true, message: '邮箱不能为空', trigger: 'blur'}
          ]
        },
        tableData: [{
          id: 0,
          createTime: '2016-05-02',
          name: '王小虎',
          age:'',
          address: '上海市普陀区金沙江路 1518 弄',
          email: '1828849754@qq.com',
          updateTime: ''
        }],
        isShowEditDialog: false,
        judeType: 1,
        dialogTitle:"新增"
      }
    },
    mounted () {
      this.$axios.get('http://localhost:8081/user/getAllUserInfo',{
        params:{
            name: this.searchForm.name,
            address: this.searchForm.address,
            email: this.searchForm.email,
            pageSize: this.searchForm.pageSize,
            pageNum: this.searchForm.pageNum
          }
      }).then(res=>{
        if(res.data.code ===0){
          this.tableData = res.data.data.records
          this.total = res.data.data.total
        }
      })
    },
    methods: {
      search(){
        this.$axios.get('http://localhost:8081/user/getAllUserInfo',{
          params:{
              name: this.searchForm.name,
              address: this.searchForm.address,
              email: this.searchForm.email,
              pageSize: this.searchForm.pageSize,
              pageNum: this.searchForm.pageNum
            }
        }).then(res=>{
          console.log(res)
          this.tableData = res.data.data.records
          this.total = res.data.data.total
        })
      },
      addDialog() {
        this.judeType = 1
        this.dialogTitle = "新增"
        this.isShowEditDialog = true
      },
      addUser(){
        this.$refs.formFileds.validate(isValid => {
          if (isValid) {
            this.$axios.post('http://localhost:8081/user/insert',this.formFileds).then(res=>{
              if(res.data.code === 0) {
                this.$elementUI.Message({        
                  message: '新增成功',  
                  type: 'success'        
                });
                this.close()
                this.search()
              } else {
                this.$elementUI.Message({        
                  message: res.data.message,  
                  type: 'error'        
                });
                this.close()
                this.search()
              }
            })
          }
        })
        
      },
      close(){
        this.formFileds = {}
        this.isShowEditDialog = false
      },
      handleSizeChange(val) {
        // console.log(`每页 ${val} 条`);
        this.searchForm.pageSize = val
        this.search()
      },
      handleCurrentChange(val) {
        // console.log(`当前页: ${val}`);
        this.searchForm.pageNum = val
        this.search()
      },
      handleRowClick(row, event, column) {
        // 仅选中当前行
        this.setCurRowChecked(row);
      },
      handleCheckedAllAndCheckedNone(selection) {
        // 当前选中仅一行时操作-（当前表格行高亮）
        1 != selection.length && this.$refs.list.setCurrentRow();
      },
      dialogClose() {
        // 清空编辑表单
        this.formFileds = {}
        this.judeType =1
      },
      rowEdit(index, row) {
        this.setCurRowChecked(row);
        // 给编辑弹出层赋值
        // ***这里需要注意的是：因为加了排序 所以tableData的顺序和实际显示的行顺序不一样
        // for (let key in this.formFileds) {

        //   this.formFileds[key] = row[key];
        // }
        this.judeType = 2
        row && (this.formFileds = JSON.parse(JSON.stringify(row)))
        this.isShowEditDialog = true;
      },
      edit() {
        this.$refs.formFileds.validate(isValid => {

          if (isValid) {
            this.$axios.put('http://localhost:8081/user/update', this.formFileds).then(res=>{
              console.log(res)
              if(res.data.code === 0){
                this.$elementUI.Message({        
                  message: '编辑成功',  
                  type: 'success'        
                });
                this.close()
                this.search()
              }else {
                this.$elementUI.Message({        
                  message: res.data.message,  
                  type: 'error'        
                });
                this.close()
                this.search()
              }
            })
          }
          // // 保存编辑后的数据
          // Object.assign(this.tableData[id], this.formFileds);
          // this.isShowEditDialog = false;

          // // 考虑到可能编辑了日期-需要重新排序
          // // ***注意：手动排序传参和表格的default-sort属性格式不太一样
          // this.$refs.list.sort('date', 'descending');

          // this.$message.success('编辑成功');
        });
      },
      rowDel(index, row, event) {
        console.log(row);
        const _userId = row.id;
        // 让当前删除按钮失焦
        event.target.blur();
        this.$confirm('确定要删除当前行吗？', '删除', {
          comfirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          this.$axios.delete('http://localhost:8081/user/delete',{params:{userId:_userId}}).then(res=>{
            if(res.data.code === 0){
              this.$message.success('删除成功');
              this.search()
            } else{
               this.$message.error('删除失败');
               this.search()
            }
          })
        }).catch(()=>{
          this.$message.info('取消删除');
        })
      },
      // 选中当前行-当前行的复选框被勾选
      setCurRowChecked(row) {

        this.$refs.list.clearSelection();
        this.$refs.list.toggleRowSelection(row);
      }
    }
  }
</script>

<style scoped lang="less">
.el-form {
  padding: 0 10px;
}
.el-date-editor {
  width: 100% !important;
}
</style>